package top.dreamyy.pattern.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import top.dreamyy.pattern.domain.Menu;
import top.dreamyy.pattern.domain.User;
import top.dreamyy.pattern.service.PatternService;
import top.dreamyy.pattern.util.common.PatternConstants;

@Controller
public class UserController {
	/**
	 * 自动注入
	 */
	@Autowired
	@Qualifier("patternService")
	private PatternService patternService;
	
	
	/**
	 * 用户登录
	 * @param name 账户名
	 * @param password 密码
 	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/judgeUser")
	public String Judge(
			@RequestParam("name") String name,
			@RequestParam("password") String password,
			HttpSession session,
			Model model){
		System.out.println("judgeUser"+" "+name+" "+password);
		User user = patternService.judgeUser(name, password);
		System.out.println("judgeUser"+" "+user);
		if(user!=null){
			session.setAttribute(PatternConstants.USER_SESSION, user);
			List<Menu> menus = patternService.getMenu();
			session.setAttribute("menus", menus);
			model.addAttribute("user", user);
			model.addAttribute("flag", 0);
			return "main";
		}else{
			model.addAttribute("name", name);
			model.addAttribute("message", "账户名或者密码错误,请重新输入!");
			return "login";
		}
	}
	
	/**
	 * 注册保存用户
	 * @param name
	 * @param password
	 * @param stuid
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/registerUser")
	public String Save(
			@RequestParam("name") String name,
			@RequestParam("password") String password,
			@RequestParam("stuid") String stuid,
			HttpSession session,
			Model model){
		User user1 = patternService.existUser(name);
		if(user1==null){
			System.out.println("registerUSer"+" "+name+" "+password+" "+stuid);
			patternService.saveUser(name, password, stuid);
			User user = new User(name, password, stuid);
			session.setAttribute(PatternConstants.USER_SESSION, user);
			return "main";
		}else{
			model.addAttribute("message", "用户已存在!");
			model.addAttribute("password", password);
			model.addAttribute("suid", stuid);
			return "Register";
		}
		 
	}
}
